const express = require("express");
const router = express.Router();
const db = require("../sql");

router.post("/", async (req, res) => {
  const { pic } = req.body;
  if (!pic) {
    return res
      .status(400)
      .json({ success: false, message: "Picture URL is required." });
  }
  try {
    const sql = "INSERT INTO banner (pic) VALUES (?)";
    await db.query(sql, [pic]);
    res.json({ success: true, message: "Banner added successfully." });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取所有 Banners
router.get("/", async (req, res) => {
  try {
    const sql = "SELECT * FROM banner";
    const banners = await db.query(sql);
    res.json({ success: true, data: banners });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 更新 Banner
router.put("/:id", async (req, res) => {
  const { pic } = req.body;
  const { id } = req.params;
  if (!pic) {
    return res
      .status(400)
      .json({ success: false, message: "Picture URL is required." });
  }
  try {
    const sql = "UPDATE banner SET pic = ? WHERE id = ?";
    await db.query(sql, [pic, id]);
    res.json({ success: true, message: "Banner updated successfully." });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 删除 Banner
router.delete("/:id", async (req, res) => {
  const { id } = req.params;
  try {
    const sql = "DELETE FROM banner WHERE id = ?";
    await db.query(sql, [id]);
    res.json({ success: true, message: "Banner deleted successfully." });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router;
